package com.lintf.devdemo.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.lintf.devdemo.common.Result;
import com.lintf.devdemo.common.ResultCode;
import com.lintf.devdemo.dao.UserInfoMapper;
import com.lintf.devdemo.entity.dto.ExportUserInfoExcelDto;
import com.lintf.devdemo.entity.dto.ImportUserInfoExcelDto;
import com.lintf.devdemo.entity.po.UserAccount;
import com.lintf.devdemo.entity.po.UserInfo;
import com.lintf.devdemo.entity.vo.ExportUserInfoExcelVo;
import com.lintf.devdemo.error.BusinessException;
import com.lintf.devdemo.service.ExcelFileService;
import com.lintf.devdemo.service.UserInfoService;
import com.lintf.devdemo.service.UserService;
import com.lintf.devdemo.utils.ChangeChinesePinyinUtil;
import com.lintf.devdemo.utils.excelUtil.ExcelUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @ system:Window
 * @ author:lin tingfeng
 * @ data:2022/11/04-10:11
 * @ package_name:com.lintf.devdemo.service.Impl
 * @ project_name:DevDemo
 * @ desc:
 */
@Service
public class ExcelFileServiceImpl implements ExcelFileService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
//    @Autowired
//    private DeiUtils deiUtils;

//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public Result importUserInfoExcel(MultipartFile file) throws Exception {
//        JSONArray jsonArray = deiUtils.getExcelMessage("USER_INFO_IMPORT", file);
//        if (jsonArray == null || jsonArray.size() == 0) {
//            throw new BusinessException("导入表格没有数据！");
//        }
//        JSONObject data = jsonArray.getJSONObject(0);
//        JSONArray array = data.getJSONArray("rows");
//        List<Map> arrList = array.toJavaList(Map.class);
//        List<UserAccount> userAccountList = new ArrayList<>();
////        List<UserInfo> userInfoList = new ArrayList<>();
//        int row = 2;
//        for (Map object : arrList) {
//            row++;
//            ImportUserInfoExcelDto dto = JSONObject.parseObject(JSONObject.toJSONString(object), ImportUserInfoExcelDto.class);
//            UserAccount userAccount = JSONObject.parseObject(JSONObject.toJSONString(dto), UserAccount.class);
//            UserInfo userInfo = JSONObject.parseObject(JSONObject.toJSONString(dto), UserInfo.class);
//            if (StringUtils.isBlank(userAccount.getAccount())) {
//                throw new BusinessException("第" + row + "行用户账号不能为空！");
//            }
//            if (StringUtils.isBlank(userAccount.getPassword())) {
//                throw new BusinessException("第" + row + "行用户密码不能为空！");
//            }
//            if (StringUtils.isBlank(userInfo.getName())) {
//                throw new BusinessException("第" + row + "行用户姓名不能为空！");
//            }
//            if (userInfo.getAge() == null) {
//                throw new BusinessException("第" + row + "行用户年龄不能为空！");
//            }
//            if (StringUtils.isNotBlank(userInfo.getEmail())) {
//                String suffix = ".com";
//                boolean result = userInfo.getEmail().endsWith(suffix);
//                if (!result) {
//                    throw new BusinessException("第" + row + "行用户邮箱地址格式不正确!");
//                }
//            }
//            // 新增user_info表数据
////            userInfoList.add(userInfo);
//            userInfoMapper.insert(userInfo);
//            // 新增user_account表数据
//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("name", userInfo.getName());
//            queryWrapper.eq("age", userInfo.getAge());
//            queryWrapper.eq("email", userInfo.getEmail());
//            Integer userId = userInfoMapper.selectOne(queryWrapper).getId();
//            userAccount.setUserId(userId);
//            userAccountList.add(userAccount);
//        }
//        boolean insertUserAccountBatch = userService.insertUserAccountBatch(userAccountList);
//        if (insertUserAccountBatch == true) {
//            return new Result(CodeEnum.SUCCESS.get(), null, "导入成功");
//        }
//        return new Result(CodeEnum.BUSINESS_ERROR.get(), null, "导入失败");
//    }
//
//    @Override
//    public void exportUserInfoExcel(HttpServletRequest request, HttpServletResponse response, ExportUserInfoExcelDto dto) {
//        // 参数格式转换
////        Map<String, Object> params = JSON.parseObject(JSON.toJSONString(dto), Map.class);
//        // 查询导出数据
//        List<ExportUserInfoExcelVo> list = userInfoMapper.exportUserInfoExcel(dto);
//        //转下Map （必要）
//        List<BeanMap> collect = list.stream().map(BeanMap::create).collect(Collectors.toList());
//        String modelCode = "USER_INFO_EXPORT";
//        JSONObject data = new JSONObject();
//        data.put("single", new JSONObject());
//        data.put("rows", collect);
//
//        JSONArray array = new JSONArray();
//        array.add(data);
//
//        deiUtils.export(modelCode, array, request, response);
//    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Result importUserInfoExcel(MultipartFile file) throws Exception {
        List<ImportUserInfoExcelDto> users = ExcelUtils.readMultipartFile(file, ImportUserInfoExcelDto.class);
        List<UserAccount> userAccountList = new ArrayList<>();
        List<UserInfo> userInfoList = new ArrayList<>();
        for (ImportUserInfoExcelDto user : users) {
            UserInfo userInfo = JSONObject.parseObject(JSONObject.toJSONString(user), UserInfo.class);
            if (StringUtils.isBlank(user.getName())) {
                throw new BusinessException(ResultCode.FAILED.getCode(), "第" + user.getRowNum() + "行" + user.getRowTips());
            }
            if (user.getAge() == null) {
                throw new BusinessException(ResultCode.FAILED.getCode(), "第" + user.getRowNum() + "行" + user.getRowTips());
            }
            if (StringUtils.isNotBlank(user.getEmail())) {
                String suffix = ".com";
                boolean result = user.getEmail().endsWith(suffix);
                if (!result) {
                    throw new BusinessException(ResultCode.FAILED.getCode(), "第" + user.getRowNum() + "行用户邮箱地址格式不正确!");
                } else if (StringUtils.isNotBlank(user.getRowTips())) {
                    throw new BusinessException(ResultCode.FAILED.getCode(), "第" + user.getRowNum() + "行" + user.getRowTips());
                }
            }
            // 新增user_info表数据
            if (StringUtils.isEmpty(userInfo.getId())) {
                userInfo.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            }
            userInfo.setCreatorId("export");
            userInfo.setCreateTime(LocalDateTime.now());
            userInfoList.add(userInfo);
            // 新增user_account表数据
            UserAccount userAccount = new UserAccount();
            Map<String, String> name = ChangeChinesePinyinUtil.changeChinesePinyin(userInfo.getName());
            userAccount.setAccount(name.get("fullPinyin"));
            userAccount.setPassword("123");
            userAccount.setUserId(userInfo.getId());
            userAccount.setCreatorId("export");
            userAccount.setCreateTime(LocalDateTime.now());
            userAccountList.add(userAccount);
        }
        boolean insertUserAccountBatch = userService.insertUserAccountBatch(userAccountList);
        boolean insertUserInfoBatch = userInfoService.insertUserInfoBatch(userInfoList);
        if (insertUserAccountBatch == true && insertUserInfoBatch) {
            return Result.success(null, "导入成功");
        }
        return Result.failed("导入失败");
    }

    @Override
    public void exportUserInfoExcel(HttpServletResponse response, ExportUserInfoExcelDto dto) {
        // 表头数据
//        List<Object> head = Arrays.asList("用户主键ID", "用户名称", "用户年龄", "用户邮箱地址","用户账号","用户密码");
        List<ExportUserInfoExcelVo> exportUserInfoExcelVos = userInfoMapper.exportUserInfoExcel(dto);
        // 将数据汇总
//        List<List<Object>> sheetDataList = new ArrayList<>();
//        sheetDataList.add(head);
//        sheetDataList.add(exportUserInfoExcelVos);
        // 导出数据
        ExcelUtils.export(response, "用户信息Excel", exportUserInfoExcelVos, ExportUserInfoExcelVo.class);
    }
}
